/**
 * 
 */
package org.demetra.port;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.logging.Logger;

import com.ericsson.otp.erlang.OtpErlangDecodeException;
import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpInputStream;
import com.ericsson.otp.erlang.OtpOutputStream;

/**
 * @author vjache
 *
 */
public abstract class WorkerBase implements Runnable{

	private Logger logger;
	
	private InputStream in = System.in;
	private OutputStream out = System.out;
//	private PrintStream err = System.err;
	
	protected WorkerBase() throws FileNotFoundException
	{
		String clsName = getClass().getSimpleName();
		logger = Logger.getLogger(clsName);
	}

	protected final void sendOtpObject(OtpErlangObject aOtpObj) throws IOException {
		OtpOutputStream erlOut = new OtpOutputStream(aOtpObj);
		byte[] buff=erlOut.toByteArray();
		intToBytes(buff.length+1,out);
		out.write(131);
		out.write(buff);
	}

	protected final OtpErlangObject receiveOtpObject() throws IOException, OtpErlangDecodeException {
		int size =intFromBytes(in);
		byte buff[]=new byte[size];
		for(int i=0;i<size;i++) {
			byte b = (byte)in.read();
			buff[i]=b;
		}//System.err.write(in.read());
		OtpInputStream erlIn = new OtpInputStream(buff);
		return erlIn.read_any();
	}

	private static int intFromBytes(InputStream stream) throws IOException {
		int i = stream.read();
		//System.err.println(String.format("Byte read %s.",i));
		for(int k = 1; k < 4; k++) {
			i = Integer.rotateLeft(i, 8);
			//System.err.println(String.format("Byte << %s.",i));
			i |= stream.read();
			//System.err.println(String.format("Byte i |= stream.read() %s.",i));
		}
		return i;
	}
	
	private static void intToBytes(int i, OutputStream stream) throws IOException {
		for(int k = 0; k < 4; k++) {
			i = Integer.rotateLeft(i, 8);
			stream.write(i);
		}
	}
	
	protected final Logger logger()
	{
		return logger;
	}
}
